import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'

export function setCookie(key: string, value: string, expires?: number) {
  Cookies.set(key, value, expires ? { expires } : {})
}

export function clearCookie() {
  document.cookie = ''
}

export function throttle(fn: Function, ms: number) {
  let lastTime = 0
  return () => {
    if (Date.now() - lastTime < ms) {
      return Promise.reject(new Error('调用过于频繁，请稍后重试'))
    }
    lastTime = Date.now()
    return Promise.resolve(fn())
  }
}

export function showErrorMsg(msg: string) {
  ElMessage({
    message: msg,
    grouping: true,
    type: 'error',
  })
}

export function showInfoMsg(msg: string) {
  ElMessage({
    message: msg,
    grouping: true,
    type: 'info',
  })
}

export function getRelativeTime(time: number) {
  const now = Date.now()
  const hour = 3600 * 1000
  const day = 86400 * 1000
  if (now - time <= hour) {
    return '1小时内活跃'
  }
  else if (now - time <= day) {
    return '今日活跃'
  }
  else if (now - time <= day * 2) {
    return '两天内活跃'
  }
  else if (now - time <= day * 3) {
    return '三天内活跃'
  }
  else if (now - time <= day * 7) {
    return '本周活跃'
  }
  else {
    return '一周内没有活动'
  }
}